/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.watcher.jade;

import jade.core.AID;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
import java.util.prefs.Preferences;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openide.util.NbPreferences;
import pl.tom.social.common.jade.JadeHandler;
import pl.tom.social.watcher.agent.WatcherAdminAgent;
import pl.tom.social.watcher.agent.WatcherAgent;
import pl.tom.social.watcher.gui.options.WatcherSettingsPanel;

/**
 *
 * @author Tom
 */
public class LocalJade extends JadeHandler {

	private static final Logger logger = Logger.getLogger(LocalJade.class);
	private static LocalJade instance = null;

	private LocalJade() {
	}

	public static synchronized LocalJade getInstance() {
		if (instance == null) {
			instance = new LocalJade();
		}
		return instance;
	}


	public synchronized void newAgent(AID receiver, String server) {
		String agentName = getAgentName(WatcherAgent.getNumberOfRunningAgents());
		WatcherAgent agent = new WatcherAgent(server);
		addAgent(agent, agentName);
	}

	public synchronized void cancelAgent(int nr) {
		String agentName = getAgentName(nr);
		deleteAgent(agentName);
	}

	private String getAgentName(int nr) {
		return "watcher-" + nr;
	}

	@Override
	public synchronized void connectToMainContainer() {
		stopJade();

		logger.log(Level.DEBUG, "Connecting to main container");

		Preferences pref = NbPreferences.forModule(WatcherSettingsPanel.class);
		String mainHost = pref.get("mainHost", "127.0.0.1");
		String mainPort = pref.get("mainPort", "8888");
		Profile pMain = new ProfileImpl();
		pMain.setParameter(Profile.MAIN, "false");
		pMain.setParameter(Profile.MAIN_HOST, mainHost);
		pMain.setParameter(Profile.MAIN_PORT, mainPort);

		jade.core.Runtime rt = jade.core.Runtime.instance();
		container = rt.createAgentContainer(pMain);

		try {
			admin = WatcherAdminAgent.getInstance();
			AgentController ac = container.acceptNewAgent("watcherAdmin", admin);
			ac.start();
		} catch(StaleProxyException ex) {
			logger.log(Level.ERROR, null, ex);
		}
	}
}
